package test.enumtest;

import java.util.Map;
import java.util.Optional;
import java.util.function.DoubleBinaryOperator;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toMap;

/**
 * @author yachao.guo
 * @date 2019-05-24 15:33
 */
public enum Operation {

    PLUS("+", (x, y) -> x + y),
    MINUS("-", (x, y) -> x - y),
    TIMES("*", (x, y) -> x * y),
    DICIDE("/", (x, y) -> x / y);

    private String symbol;

    private DoubleBinaryOperator bo;

    Operation(String symbol, DoubleBinaryOperator bo) {
        this.symbol = symbol;
        this.bo = bo;
    }

    public double apply(double x, double y) {
        return bo.applyAsDouble(x, y);
    }

    private static final Map<String, Operation> stringToOperation = Stream.of(Operation.values()).collect(toMap(Operation::getSymbol, o -> o));

    public static Optional<Operation> fromString(String symbol) {
        return Optional.ofNullable(stringToOperation.get(symbol));
    }

    @Override
    public String toString() {
        return symbol;
    }

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }
}
